
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>3.1 属于 · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.2">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="3.2包含.html" />
    
    
    <link rel="prev" href="3模型关系.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Introduction
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="1.写在前面的话.html">
            
                <a href="1.写在前面的话.html">
            
                    
                    写在前面的话
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="2.搭建环境.html">
            
                <a href="2.搭建环境.html">
            
                    
                    第一章 搭建环境
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4" >
            
                <span>
            
                    
                    第二章 模型定义
            
                </span>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.1" data-path="3.sequelize 实例变量.html">
            
                <a href="3.sequelize 实例变量.html">
            
                    
                    2.1 实例变量方法
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.2" data-path="4.定义一个模型.html">
            
                <a href="4.定义一个模型.html">
            
                    
                    2.2 定义一个模型
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.3" data-path="5.模型字段类型.html">
            
                <a href="5.模型字段类型.html">
            
                    
                    2.3 模型字段类型
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.4" data-path="6.导入与配置.html">
            
                <a href="6.导入与配置.html">
            
                    
                    2.3 导入与配置
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="3模型关系.html">
            
                <a href="3模型关系.html">
            
                    
                    第三章 模型关系
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter active" data-level="1.5.1" data-path="3.1属于.html">
            
                <a href="3.1属于.html">
            
                    
                    3.1 属于
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="3.2包含.html">
            
                <a href="3.2包含.html">
            
                    
                    3.2 包含
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="3.3一对多.html">
            
                <a href="3.3一对多.html">
            
                    
                    3.3 一对多
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4" data-path="3.4多对多.html">
            
                <a href="3.4多对多.html">
            
                    
                    3.4 多对多
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.5" data-path="3.5多态一对多.html">
            
                <a href="3.5多态一对多.html">
            
                    
                    3.5 多态一对多
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.6" data-path="3.6多态多对多.html">
            
                <a href="3.6多态多对多.html">
            
                    
                    3.6 多态多对多
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.7" data-path="3.7关系嵌套.html">
            
                <a href="3.7关系嵌套.html">
            
                    
                    3.7 关系嵌套
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="4模型查询.html">
            
                <a href="4模型查询.html">
            
                    
                    第四章 模型查询
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="5查询范围.html">
            
                <a href="5查询范围.html">
            
                    
                    第五章 查询范围 Scope (预定义查询条件)
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="6生命周期函数.html">
            
                <a href="6生命周期函数.html">
            
                    
                    第六章 生命周期函数 Hook
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="7migrate.html">
            
                <a href="7migrate.html">
            
                    
                    第七章 数据库迁移 Migrate
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="8tabel2model.html">
            
                <a href="8tabel2model.html">
            
                    
                    第八章 根据 Table 生成 Model
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >3.1 属于</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="&#x5C5E;&#x4E8E;">&#x5C5E;&#x4E8E;</h1>
<h3 id="&#x58F0;&#x660E;&#x5C5E;&#x4E8E;&#x5173;&#x7CFB;">&#x58F0;&#x660E;&#x5C5E;&#x4E8E;&#x5173;&#x7CFB;</h3>
<p>&#x58F0;&#x660E;&#x662F;&#x5C5E;&#x4E8E;&#x5173;&#x7CFB;&#x7684;&#x65B9;&#x6CD5;&#x662F; <code>belongsTo</code></p>
<pre><code class="lang-ts">Book.belongsTo(User);
</code></pre>
<p><code>Book</code> &#x662F;&#x4E3B;&#x4F53;&#x53D1;&#x8D77;&#x6A21;&#x578B;&#xFF0C;&#x800C; <code>User</code> &#x662F;&#x76EE;&#x6807;&#x6A21;&#x578B;&#x3002;&#x8FD9;&#x6837;&#x58F0;&#x660E;&#x4F1A;&#x5728; Book &#x4E0A;&#x9762;&#x589E;&#x52A0; <code>setUser</code> / <code>createUser</code> / <code>User</code> &#x4FE9;&#x4E2A;&#x65B9;&#x6CD5;&#x4E0E;&#x4E00;&#x4E2A;&#x5C5E;&#x6027;&#xFF0C;&#x901A;&#x8FC7; options &#x91CC;&#x9762;&#x7684; <code>as: &apos;Some&apos;</code>&#xFF0C;&#x6765;&#x8BA9;&#x540D;&#x79F0;&#x53D8;&#x6210; <code>setSome</code> / <code>createSser</code> / <code>Some</code>&#x3002;&#x4E14;&#x5728; Book &#x8868;&#x91CC;&#x9762;&#x4F1A;&#x81EA;&#x52A8;&#x589E;&#x52A0;&#x4E00;&#x4E2A; <code>UserId</code> &#x7684;&#x5B57;&#x6BB5;&#x6765;&#x8BB0;&#x5F55; User &#x7684; id &#x503C;&#xFF0C;&#x901A;&#x8FC7;&#x8BBE;&#x7F6E; options &#x91CC;&#x9762;&#x7684; <code>foreignKey: &apos;user_id&apos;</code>&#xFF0C;&#x6765;&#x4FEE;&#x6539;&#x81EA;&#x52A8;&#x589E;&#x52A0;&#x5B57;&#x6BB5;&#x7684;&#x540D;&#x79F0;&#x3002;</p>
<p>&#x5018;&#x82E5;&#x4F60;&#x5341;&#x5206;&#x8BA8;&#x538C;&#x9A7C;&#x5CF0;&#x539F;&#x5219;&#xFF0C;&#x559C;&#x6B22;&#x4E0B;&#x5212;&#x7EBF;&#x5206;&#x5272;&#x7684;&#x914D;&#x7F6E;&#xFF0C;&#x5E76;&#x4E14;&#x671F;&#x671B;&#x6240;&#x6709;&#x8868;&#x90FD;&#x8FD9;&#x6837;&#xFF0C;&#x53EF;&#x4EE5;&#x5728;&#x521D;&#x59CB;&#x5316;&#x6570;&#x636E;&#x5E93;&#x8FDE;&#x63A5;&#x7684;&#x65F6;&#x5019;&#x914D;&#x7F6E; <code>define.underscored</code>&#xFF0C;&#x5B83;&#x4F1A;&#x9ED8;&#x6210;&#x4E3A;&#x4F60;&#x6240;&#x6709; define &#x7684; &#x9ED8;&#x8BA4; options&#x3002;</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> sequelize = <span class="hljs-keyword">new</span> Sequelize(<span class="hljs-string">&apos;nodelover&apos;</span>, <span class="hljs-string">&apos;root&apos;</span>, <span class="hljs-string">&apos;&apos;</span>, {
  host: <span class="hljs-string">&apos;localhost&apos;</span>,
  dialect: <span class="hljs-string">&apos;mysql&apos;</span>,
  define: {
      underscored: <span class="hljs-literal">true</span>,
  }    ,
  pool: {
    max: <span class="hljs-number">5</span>,
    min: <span class="hljs-number">0</span>,
    idle: <span class="hljs-number">10000</span>
  },
});
</code></pre>
<h3 id="&#x5C0F;&#x6817;&#x5B50;">&#x5C0F;&#x6817;&#x5B50;</h3>
<p>&#x63A5;&#x4E0B;&#x6765;&#xFF0C;&#x540C;&#x6837;&#x901A;&#x8FC7;&#x4E00;&#x4E2A;&#x4F8B;&#x5B50;&#x6765;&#x8BF4;&#x660E;&#x5C5E;&#x4E8E;&#x5173;&#x7CFB;&#x3002;&#x5C31;&#x7740;&#x4E4B;&#x524D;&#x7684; User &#x4E0E; Book &#x6A21;&#x578B;&#x5B9A;&#x4E49;&#x505A;&#x4E00;&#x4E9B;&#x4FEE;&#x6539;&#x3002;</p>
<p>&#x63A5;&#x53E3;&#x662F;&#x652F;&#x6301;&#x7EE7;&#x627F;&#x7684;&#xFF0C;&#x6CA1;&#x5FC5;&#x8981;&#x628A; UserAttributes &#x91CC;&#x9762;&#x7684;&#x5C5E;&#x6027;&#x518D;&#x5199;&#x4E00;&#x6B21;&#xFF0C;&#x76F4;&#x63A5;&#x7EE7;&#x627F;&#x4E00;&#x4E0B;&#x5C31;&#x597D;&#x4E86;&#x3002;&#x5E76;&#x4E14;&#x4E3A;&#x52A0;&#x5F3A;&#x4E00;&#x4E0B;&#x8BB0;&#x5FC6;&#xFF0C;&#x518D;&#x6B21;&#x9610;&#x8FF0;&#x4E00;&#x4E0B;<strong>&#x5C5E;&#x6027;&#x63A5;&#x53E3;&#x4E0E;&#x5B9E;&#x4F8B;&#x63A5;&#x53E3;&#x7684;&#x533A;&#x522B;</strong>&#xFF0C;<code>attr</code> &#x91CC;&#x9762;&#x58F0;&#x660E;&#x7684;&#x662F; create &#x521B;&#x5EFA;&#x7684;&#x65F6;&#x5019;&#x9700;&#x8981;&#x4F20;&#x9012;&#x7684;&#x5C5E;&#x6027;&#xFF0C;&#x800C; <code>instance</code> &#x63A5;&#x53E3;&#x91CC;&#x9762;&#x7684;&#x90FD;&#x662F; sequelize &#x52A8;&#x6001;&#x7ED9;&#x7C7B;&#x6DFB;&#x52A0;&#x7684;&#x65B9;&#x6CD5;&#x4E0E;&#x5C5E;&#x6027;&#x3002;</p>
<h4 id="1-&#x65B0;&#x5EFA;-userts">1. &#x65B0;&#x5EFA; user.ts</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> Sequelize from <span class="hljs-string">&apos;sequelize&apos;</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> UserAttributes {
  email: <span class="hljs-built_in">string</span>;
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> UserInstance <span class="hljs-keyword">extends</span> Sequelize.Instance&lt;UserAttributes&gt;, UserAttributes {
  id: <span class="hljs-built_in">number</span>;
  createdAt: <span class="hljs-built_in">Date</span>;
  updatedAt: <span class="hljs-built_in">Date</span>;
  say(): <span class="hljs-built_in">void</span>;

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserDefine</span>(<span class="hljs-params">sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes</span>): <span class="hljs-title">Sequelize</span>.<span class="hljs-title">Model</span>&lt;<span class="hljs-title">UserInstance</span>, <span class="hljs-title">UserAttributes</span>&gt;  </span>{
    <span class="hljs-keyword">const</span> S = dataTypes;
    <span class="hljs-keyword">const</span> User = sequelize.define&lt;UserInstance, UserAttributes&gt;
    (<span class="hljs-string">&apos;User&apos;</span>, {
        email: S.STRING,
        name: S.STRING
    });

    (User as <span class="hljs-built_in">any</span>).prototype.say = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-keyword">this</span>: UserInstance</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;name &apos;</span> + <span class="hljs-keyword">this</span>.name);
    };

    (User as <span class="hljs-built_in">any</span>).associate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">models</span>)</span>{

    }
    <span class="hljs-keyword">return</span> User;
}
</code></pre>
<p>&#x5728;&#x6A21;&#x578B;&#x91CC;&#x9762;&#xFF0C;&#x53EF;&#x4EE5;&#x5728;&#x9759;&#x6001; associate &#x65B9;&#x6CD5;&#x6765;&#x5B9A;&#x4E49;&#x6A21;&#x578B;&#x4E4B;&#x95F4;&#x7684;&#x5173;&#x7CFB;&#xFF0C;&#x8FD9;&#x662F;&#x5B98;&#x65B9;&#x6240;&#x63A8;&#x8350;&#x7684;&#xFF0C;&#x5047;&#x5982;&#x4F7F;&#x7528;&#x5B98;&#x65B9;&#x63D0;&#x4F9B;&#x7684; migrate &#x5DE5;&#x5177;&#x4F1A;&#x81EA;&#x52A8;&#x6267;&#x884C;&#x8BE5;&#x65B9;&#x6CD5;&#x3002;</p>
<p>&#x5728; <code>prototype</code> &#x4E0A;&#x9762;&#x52A0;&#x4E86;&#x4E00;&#x4E2A; say &#x5B9E;&#x4F8B;&#x65B9;&#x6CD5;&#xFF0C;&#x6240;&#x4EE5;&#x5728; <code>instace</code> &#x63A5;&#x53E3;&#x91CC;&#x9762;&#x58F0;&#x660E;&#x4E00;&#x4E0B; say &#x65B9;&#x6CD5;&#x3002;</p>
<h4 id="2bookts">2.book.ts</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> Sequelize from <span class="hljs-string">&apos;sequelize&apos;</span>;
<span class="hljs-keyword">import</span> {UserInstance, UserAttributes} from <span class="hljs-string">&apos;./User&apos;</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> BookAttributes {
  status: <span class="hljs-string">&quot;inSale&quot;</span> | <span class="hljs-string">&quot;noSale&quot;</span>;
  description: <span class="hljs-built_in">string</span>;
  title: <span class="hljs-built_in">string</span>;
  author: <span class="hljs-built_in">string</span>;
}


<span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> BookInstance <span class="hljs-keyword">extends</span> Sequelize.Instance&lt;BookAttributes&gt;, BookAttributes{
  id: <span class="hljs-built_in">number</span>;
  createdAt: <span class="hljs-built_in">Date</span>;
  updatedAt: <span class="hljs-built_in">Date</span>;

  setUser: Sequelize.BelongsToSetAssociationMixin&lt;UserInstance, <span class="hljs-built_in">number</span>&gt;;
  createUser: Sequelize.BelongsToCreateAssociationMixin&lt;UserAttributes&gt;;
  User: Sequelize.BelongsToGetAssociationMixin&lt;UserInstance&gt;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BookDefine</span>(<span class="hljs-params">sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes</span>): <span class="hljs-title">Sequelize</span>.<span class="hljs-title">Model</span>&lt;<span class="hljs-title">BookInstance</span>, <span class="hljs-title">BookAttributes</span>&gt; </span>{
  <span class="hljs-keyword">const</span> S = dataTypes;
  <span class="hljs-keyword">const</span> Book =  sequelize.define&lt;BookInstance, BookAttributes&gt;(<span class="hljs-string">&apos;Book&apos;</span>, {
    id: {
        <span class="hljs-keyword">type</span>: S.INTEGER,
        autoIncrement: <span class="hljs-literal">true</span>,
        primaryKey: <span class="hljs-literal">true</span>,
        unique: <span class="hljs-literal">true</span>
    },
    description: S.TEXT,
    status: {
        <span class="hljs-keyword">type</span>: S.ENUM,
        values: [<span class="hljs-string">&apos;inSale&apos;</span>, <span class="hljs-string">&apos;noSale&apos;</span>],
        validate: {
            isIn: {
                args: [[<span class="hljs-string">&apos;inSale&apos;</span>, <span class="hljs-string">&apos;noSale&apos;</span>]],
                msg: <span class="hljs-string">&quot;status field must be inSale or noSale&quot;</span>
            }
        }
    },
    title:{
        <span class="hljs-keyword">type</span>: S.STRING,
        allowNull: <span class="hljs-literal">false</span>,
        <span class="hljs-keyword">get</span>(<span class="hljs-keyword">this</span>: BookInstance) {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getDataValue(<span class="hljs-string">&apos;author&apos;</span>) + <span class="hljs-string">&apos; - &apos;</span> + <span class="hljs-keyword">this</span>.getDataValue(<span class="hljs-string">&apos;title&apos;</span>);
        }
    },
    author: {
        <span class="hljs-keyword">type</span>: S.STRING,
        allowNull: <span class="hljs-literal">false</span>,
        <span class="hljs-keyword">set</span>(val: <span class="hljs-built_in">string</span>){
            <span class="hljs-keyword">this</span>.setDataValue(<span class="hljs-string">&apos;author&apos;</span>, val.toLowerCase());
        }
    }},{
        comment: <span class="hljs-string">&quot;&#x56FE;&#x4E66;&#x8868;&quot;</span>, <span class="hljs-comment">// &#x8868;&#x6CE8;&#x91CA;</span>
        indexes: [  <span class="hljs-comment">// &#x8868;&#x7D22;&#x5F15;</span>
            {
                fields: [<span class="hljs-string">&apos;id&apos;</span>]
            }
        ],
        classMethods: {
            <span class="hljs-comment">// associate: function(models){} &#x7B2C;&#x4E00;&#x79CD;</span>
        }
    });
    <span class="hljs-comment">// &#x7B2C;&#x4E8C;&#x79CD;</span>
    (Book as <span class="hljs-built_in">any</span>).associate = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-keyword">this</span>: <span class="hljs-keyword">typeof</span> Book, models: <span class="hljs-built_in">any</span></span>)</span>{
        <span class="hljs-keyword">this</span>.belongsTo(models.User);
    }

    <span class="hljs-keyword">return</span> Book;
}
</code></pre>
<p><strong>&#x7279;&#x522B;&#x6CE8;&#x610F;</strong> &#x7B2C;&#x4E00;&#x79CD;&#x5199;&#x6CD5;&#x5728; v4 &#x7248;&#x672C;&#x5C06;&#x4F1A;&#x88AB;&#x79FB;&#x9664;&#x3002;&#x5177;&#x4F53;&#x53EF;&#x4EE5;&#x67E5;&#x770B;&#x5B98;&#x65B9;&#x7684;<code>&#x5982;&#x4F55;&#x5347;&#x7EA7;&#x5230; v4&#x7248;&#x672C;&#xFF1F;</code>&#x6587;&#x6863;&#x3002;</p>
<p>&#x5728; define &#x65B9;&#x6CD5;&#x7684; options &#x53C2;&#x6570;&#x91CC;&#x662F;&#x6709; <code>classMethods</code> &#x914D;&#x7F6E;&#x9879;&#x7684;&#xFF0C;&#x53EF;&#x4EE5;&#x6307;&#x5B9A;&#x6A21;&#x578B;&#x7684;&#x9759;&#x6001;&#x65B9;&#x6CD5;&#xFF0C;&#x6240;&#x4EE5;&#x53EF;&#x4EE5;&#x6709;&#x4FE9;&#x79CD;&#x5199;&#x6CD5;&#x3002;&#x8FD9;&#x91CC;&#x7528;&#x7684;&#x662F;&#x76F4;&#x63A5;&#x5199;&#xFF0C;&#x4E5F;&#x5C31;&#x662F;&#x7B2C;&#x4E8C;&#x79CD;&#x5199;&#x6CD5;&#x3002;&#x5728; <code>associate</code> &#x9759;&#x6001;&#x65B9;&#x6CD5;&#x5185;&#xFF0C; <code>this</code> &#x6307;&#x7684;&#x5C31;&#x662F; <code>Book</code>&#xFF0C;&#x800C;&#x4F20;&#x9012;&#x7684; models &#x91CC;&#x9762;&#x6709;&#x6240;&#x6709; define &#x8FC7;&#x7684;&#x6A21;&#x578B;&#xFF0C;&#x8FD9;&#x91CC;&#x5B9A;&#x4E49;&#x7684;&#x5173;&#x7CFB;&#x5C31;&#x662F;, Book &#x6A21;&#x578B;&#x5C5E;&#x4E8E; User&#xFF0C;&#x6240;&#x4EE5;&#x4F1A;&#x5728; Book &#x5B9E;&#x4F8B;&#x4E0A;&#x9762;&#x6DFB;&#x52A0; <code>setUser</code> / <code>createUser</code> / <code>User</code>&#x3002;</p>
<p>sequelize &#x52A8;&#x6001;&#x6DFB;&#x52A0;&#x4E86;&#x8FD9;&#x4E9B;&#x65B9;&#x6CD5;&#xFF0C;&#x4F46;&#x662F; typescript &#x662F;&#x4E0D;&#x77E5;&#x9053;&#x7684;&#xFF0C;&#x6240;&#x4EE5;&#x9700;&#x8981;&#x81EA;&#x5DF1;&#x53BB;&#x58F0;&#x660E;&#xFF0C;&#x6240;&#x4EE5;&#x5C31;&#x6709;&#x4E86;&#x3002;</p>
<pre><code class="lang-ts">  setUser: Sequelize.BelongsToSetAssociationMixin&lt;UserInstance, <span class="hljs-built_in">number</span>&gt;;
  createUser: Sequelize.BelongsToCreateAssociationMixin&lt;UserAttributes&gt;;
  User: Sequelize.BelongsToGetAssociationMixin&lt;UserInstance&gt;
</code></pre>
<p>&#x8FD9;&#x4E9B; Mixin &#x662F;&#x7531;&#x5B9A;&#x4E49;&#x5E93;&#x63D0;&#x4F9B;&#x7684;&#x4E00;&#x4E9B;&#x63A5;&#x53E3;&#x3002;</p>
<h4 id="3indexts">3.index.ts</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> Sequelize from <span class="hljs-string">&apos;sequelize&apos;</span>;

<span class="hljs-keyword">const</span> sequelize = <span class="hljs-keyword">new</span> Sequelize(<span class="hljs-string">&apos;nodelover&apos;</span>, <span class="hljs-string">&apos;root&apos;</span>, <span class="hljs-string">&apos;&apos;</span>, {
  host: <span class="hljs-string">&apos;localhost&apos;</span>,
  dialect: <span class="hljs-string">&apos;mysql&apos;</span>,

  pool: {
    max: <span class="hljs-number">5</span>,
    min: <span class="hljs-number">0</span>,
    idle: <span class="hljs-number">10000</span>
  },
});

<span class="hljs-keyword">import</span> UserDefined , { UserAttributes, UserInstance  }  from <span class="hljs-string">&apos;./user&apos;</span>;
<span class="hljs-keyword">import</span> BookDefined, {BookAttributes, BookInstance} from <span class="hljs-string">&apos;./book&apos;</span>;

async <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> User = sequelize.import&lt;UserInstance, UserAttributes&gt;(<span class="hljs-string">&apos;./user&apos;</span>);
    <span class="hljs-keyword">const</span> Book = sequelize.import&lt;BookInstance, BookAttributes&gt;(<span class="hljs-string">&apos;./book&apos;</span>);

    <span class="hljs-built_in">Object</span>.keys(sequelize.models).forEach(modelName =&gt; {
      <span class="hljs-keyword">const</span> model = (sequelize.models[modelName] as <span class="hljs-built_in">any</span>)
      <span class="hljs-keyword">if</span>(<span class="hljs-string">&apos;associate&apos;</span> <span class="hljs-keyword">in</span> model){
        model.associate(sequelize.models)
      }
    })

    await sequelize.sync();

    <span class="hljs-keyword">let</span> book = await Book.create({author:<span class="hljs-string">&apos;alice&apos;</span>, description: <span class="hljs-string">&apos;typescript hand book&apos;</span>, status: <span class="hljs-string">&apos;inSale&apos;</span>,title:<span class="hljs-string">&apos;ts leaning&apos;</span>});
    <span class="hljs-keyword">let</span> user = await User.create({email:<span class="hljs-string">&apos;belovedyogurt@gmail.com&apos;</span>,name: <span class="hljs-string">&apos;yugo&apos;</span>})
    book.setUser(user);
    await book.save();
  }<span class="hljs-keyword">catch</span>(e){
    <span class="hljs-comment">// console.log(e)</span>
    <span class="hljs-keyword">if</span> (e <span class="hljs-keyword">instanceof</span> Sequelize.ValidationError) {
      <span class="hljs-built_in">console</span>.log(e.message);
    }
  }
  process.exit(<span class="hljs-number">0</span>)
</code></pre>
<p><code>sequelize.models</code> &#x5BF9;&#x8C61;&#x4E0A;&#x9762;&#x7F13;&#x5B58;&#x4E86;&#x6240;&#x6709;&#x5B9A;&#x4E49;&#x8FC7;&#x7684;&#x6A21;&#x578B;&#xFF0C;&#x901A;&#x8FC7;&#x4EE5;&#x4E0B;&#x51E0;&#x884C;&#x4EE3;&#x7801;&#xFF0C;&#x5B9E;&#x73B0;&#x4E86;&#x81EA;&#x52A8;&#x8C03;&#x7528; associate &#x65B9;&#x6CD5;&#xFF0C;&#x4E0E;&#x540C;&#x6B65;&#x6570;&#x636E;&#x5E93;&#x8868;&#x3002;</p>
<pre><code class="lang-ts"><span class="hljs-built_in">Object</span>.keys(sequelize.models).forEach(modelName =&gt; {
 <span class="hljs-keyword">const</span> model = (sequelize.models[modelName] as <span class="hljs-built_in">any</span>)
 <span class="hljs-keyword">if</span>(<span class="hljs-string">&apos;associate&apos;</span> <span class="hljs-keyword">in</span> model){
   model.associate(sequelize.models)
 }
})

await sequelize.sync();
</code></pre>
<p>&#x8FD0;&#x884C;&#x4EE5;&#x4E0A;&#x4EE3;&#x7801;&#xFF0C;&#x5728;&#x6570;&#x636E;&#x5E93;&#x91CC;&#x9762;&#x53EF;&#x4EE5;&#x770B;&#x5230;2&#x5F20;&#x8868;&#x90FD;&#x5DF2;&#x7ECF;&#x6709;&#x4E86;&#x6570;&#x636E;&#x3002;</p>
<p>&#xB7;&gt;_&lt;&#xB7;! Nice Work!</p>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="3模型关系.html" class="navigation navigation-prev " aria-label="Previous page: 第三章 模型关系">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="3.2包含.html" class="navigation navigation-next " aria-label="Next page: 3.2 包含">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"3.1 属于","level":"1.5.1","depth":2,"next":{"title":"3.2 包含","level":"1.5.2","depth":2,"path":"document/3.2包含.md","ref":"./document/3.2包含.md","articles":[]},"previous":{"title":"第三章 模型关系","level":"1.5","depth":1,"path":"document/3模型关系.md","ref":"./document/3模型关系.md","articles":[{"title":"3.1 属于","level":"1.5.1","depth":2,"path":"document/3.1属于.md","ref":"./document/3.1属于.md","articles":[]},{"title":"3.2 包含","level":"1.5.2","depth":2,"path":"document/3.2包含.md","ref":"./document/3.2包含.md","articles":[]},{"title":"3.3 一对多","level":"1.5.3","depth":2,"path":"document/3.3一对多.md","ref":"./document/3.3一对多.md","articles":[]},{"title":"3.4 多对多","level":"1.5.4","depth":2,"path":"document/3.4多对多.md","ref":"./document/3.4多对多.md","articles":[]},{"title":"3.5 多态一对多","level":"1.5.5","depth":2,"path":"document/3.5多态一对多.md","ref":"./document/3.5多态一对多.md","articles":[]},{"title":"3.6 多态多对多","level":"1.5.6","depth":2,"path":"document/3.6多态多对多.md","ref":"./document/3.6多态多对多.md","articles":[]},{"title":"3.7 关系嵌套","level":"1.5.7","depth":2,"path":"document/3.7关系嵌套.md","ref":"./document/3.7关系嵌套.md","articles":[]}]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"document/3.1属于.md","mtime":"2017-06-27T03:35:05.000Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-06-28T08:29:37.466Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-livereload/plugin.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

